import './commonDocument.scss';
import PaBaseModel from '../../core/model/PaBaseModel.js';

function commonDocumentCtrl($rootScope, $scope, $http, ngDialog, paFetchService) {
  'ngInject';
  let _this = this;
  $scope.isUploading = false;
  $scope.id = $state.params.id;
  $scope.commonType = $state.params.commonType;
  $scope.type = $state.params.type;
  $scope.role = $state.params.role;
  $scope.loginRole = JSON.parse(localStorage.getItem('userInfo')).role;
  $scope.roleName = $scope.role == 0 ? '指挥部' : $scope.role == 1 ? '总监办' : '项目部';
  // 总监办、项目部展现标段tab
  $scope.disabled = $scope.role != 0 ? false : true;


  if ( $scope.role == 1) {
    $scope.officeDisabled = true;
    // // 获取标段列表接口
    // $http
    //   .get(`${SERVER_CONTEXT}/api/userTender/getTenders?role=${$scope.role}`)
    //   .then((resp) => {
    //     $rootScope.authorizationInfo.bidsInfo = resp.data.data;
    //     this.sectionList = resp.data.data;
    //     $scope.sectionList = resp.data.data;
    //   })
  } else {
    $scope.officeDisabled = false;
    // // 获得标段数据
    // paFetchService
    //   .getSectionList()
    //   .then((resp) => {
    //     this.sectionList = resp.data.data;
    //     $scope.sectionList = resp.data.data;
    //   });
  }

  // 分页
  $scope.queryData = new PaBaseModel({
    documentName: $scope.commonType,
    recordno: '',
  });
  $scope.paginationData = {
    pageNum: 1,
    pageSize: 10,
    total: '',
  };

  $scope.reset = () => {
    $scope.queryData = new PaBaseModel({
      documentName: $scope.commonType,
      recordno: '',
    });
    $scope.queryData.markSection = $rootScope.activeBid.tenderId;
  }

  let initMoveAllFlag = false;
  $scope.moveAll = () => {
    initMoveAllFlag = !initMoveAllFlag;
    $scope.documentList.forEach((item) => {
      item.selected = initMoveAllFlag;
    });

  }

  // 分页查询档案
  $scope.initViewModel = () => {
    $http.post(`${SERVER_CONTEXT}/api/safesite/officeworkdata/selectByCondition`,
      angular.extend($scope.queryData, $scope.paginationData)).
    then((resp) => {
      $scope.documentList = resp.data.data;
      $scope.paginationData.total = resp.data.total;
    });
  };
  if ($scope.disabled) {
    $scope.initViewModel();
  }

  // 页码变化时调用方法
  $scope.pageChange = () => {
    $scope.initViewModel();
  };

  // 上传档案信息
  $scope.newData = () => {
    ngDialog.open({
      template: 'documentItemMgt',
      className: 'ngdialog-theme-default pa-special-check-item-list-theme',
      controllerAs: 'officeDataAddCtrl',
      scope: $scope,
      controller: function cfgAddCtrl($http, $scope) {
        'ngInject';
        this.category = {
          recordno: '',
          archiveName: '',
          completionTime: '',
          markSection: '',
          organization: '',
          uploader: '',
          relatedDesc: '',
          fileBeanList: [],
          fileIds: [], // 存放上传文件返回token
        };

        // this.sectionList = _this.sectionList;
        // 获得标段数据
        // paFetchService
        //   .getSectionList()
        //   .then((resp) => {
        //     this.sectionList = resp.data;
        //   });

        this.submit = (param) => {
          if ($scope.isUploading) {
            layer.alert('文件正在上传中');
          }
          // 修改表单是否提交过状态
          param.$submitted = true;

          // 表单校验
          if (param.$invalid) {
            return false;
          }
          this.category.documentType = $scope.id;
          this.category.documentName = $scope.commonType;

          let fileIdArray = this.category.fileBeanList.map(item => item.id);
          this.category.fileIds = fileIdArray.join(',');
          let reqData = this.category;
          $http({
            method: 'POST',
            url: `${SERVER_CONTEXT}/api/safesite/officeworkdata/saveRecord`,
            data: reqData,
          }).then((resp) => {
            if (resp.data.success) {
              layer.msg(resp.data.message);
              $scope.initViewModel();
              $scope.closeThisDialog();
            } else {
              layer.alert(resp.data.message);
              $scope.closeThisDialog();
            }
          });
        }
      },
    });
  };

  $scope.moveArchives = () => {
    let archivesToMove = []
    $scope.documentList.forEach((item) => {
      if (item.selected) {
        archivesToMove.push(item);
      }
    });
    if (!archivesToMove.length) {
      layer.alert('请选择文档');
      return;
    } else {
      $scope.archivesToMove = archivesToMove;
    }
    ngDialog.open({
      template: 'move',
      className: 'ngdialog-theme-default pa-special-check-item-list-theme',
      controllerAs: 'moveCtrl',
      scope: $scope,
      controller: function moveCtrl($http, $scope) {
        'ngInject';
        this.archivesToMove = $scope.archivesToMove;
        this.archiveIds = [];
        this.archivesNoStr = '';

        this.boxChange = () => {
          if (this.selectedBox && !this.selectedBox.children) {
            $http
              .post(`${SERVER_CONTEXT}/api/documentBox/getDocumentByCondition`, {
                fileType: '文件夹',
                requireType: 'file',
                checkCategoryID: this.selectedBox.checkCategoryID,
              })
              .success((respData) => {
                this.selectedBox.children = respData;
                if (this.selectedBox.children.length > 0) {
                  this.selectedFolder = this.selectedBox.children[0];
                }
              })
          } else {
            if (this.selectedBox.children.length > 0) {
              this.selectedFolder = this.selectedBox.children[0];
            }
          }
        }

        this.submit = (form) => {
          $http({
            method: 'POST',
            url: `${SERVER_CONTEXT}/api/documentBox/moveFile`,
            data: {
              ids: this.archiveIds,
              boxID: this.selectedFolder ? this.selectedFolder.boxID : this.selectedBox.boxID,
            },
          }).success((data) => {
            let failArchiveNames = '';
            data.forEach((item) => {
              if (!item.result) {
                this.archivesToMove.forEach((archive) => {
                  if (archive.recordno == item.recordNo) {
                    failArchiveNames ? failArchiveNames = archive.archiveName : failArchiveNames += ', ' + archive.archiveName;
                  }
                })
              }
            });

            if (failArchiveNames) {
              layer.msg(failArchiveNames);
            } else {
              layer.msg('文档移动成功');
            }
            $scope.initViewModel();
            $scope.closeThisDialog();
          });
        }

        this.init = () => {
          $scope.archivesToMove.forEach((item, index) => {
            if (index == 0) {
              this.archivesNoStr = item.archiveNo;
            } else {
              this.archivesNoStr += ',' + item.archiveNo;
            }
            this.archiveIds.push(item.recordno);
          });

          $http
            .get(`${SERVER_CONTEXT}/api/documentBox/getDocumentBox`)
            .success((respData) => {
              respData.forEach((item) => {
                if (item.boxRoleName == $scope.roleName) {
                  this.boxes = item.boxes;
                  this.selectedBox = this.boxes[0];
                  this.boxChange();
                  // return $http.post(`${SERVER_CONTEXT}/api/documentBox/getDocumentByCondition`, {
                  //         fileType: '文件夹',
                  //         requireType: 'file',
                  //         checkCategoryID: 3,
                  //       })
                }
              })
            })
            // .success((respData) => {
            //   console.log(respData)
            //   // let excludeBox = {};
            //   // respData.forEach((item) => {
            //   //   if (item.checkCategoryID == $scope.commonType) {
            //   //     excludeBox = item;
            //   //   }
            //   // });

            //   // respData.splice(respData.indexOf(excludeBox), 1);
            //   // this.boxList = respData;
            // })
        }

        this.init();
      },
    });
  }

  // 查看档案信息
  $scope.getArchiveDetail = (id) => {
      $scope.currentRecordId = id;
      ngDialog.open({
        template: 'archiveDetail',
        className: 'ngdialog-theme-default pa-special-check-item-list-theme',
        scope: $scope,
        controller: function($scope) {
          'ngInject';

          // 获得文档详情信息
          let str = `${SERVER_CONTEXT}/api/safesite/officeworkdata/selectByPrimaryKey/` + $scope.currentRecordId;
          $http.get(str).
          then((resp) => {
            $scope.archiveDetail = resp.data;
          });

          // 获得文件下载链接
          $scope.getDownloadSrc = (file) => {
            return `${SERVER_CONTEXT}/api/safesite/officeworkdata/download/${file.id}`;
          }

          // 进入文件预览页面
          $scope.preview = (archiveDetail) => {
            let url = $state.href('documentPreview', {
              id: archiveDetail.id,
            });
            window.open(url, '_blank');
          }
        }
      });
    }
    // 编辑档案信息
  $scope.editeditDocument = {};
  $scope.editData = (id) => {
      $scope.currentRecordId = id;
      ngDialog.open({
        template: 'editDocumentItemMgt',
        className: 'ngdialog-theme-default pa-special-check-item-list-theme',
        scope: $scope,
        controller: function($scope, paFetchService) {
          'ngInject';

          $scope.sectionList = _this.sectionList;

          let str = `${SERVER_CONTEXT}/api/safesite/officeworkdata/selectByPrimaryKey/` + $scope.currentRecordId;
          $http.get(str).
          then((resp) => {
            $scope.editeditDocument = resp.data;
          });

          // 获得标段数据
          // paFetchService
          //   .getSectionList()
          //   .then((resp) => {
          //     this.sectionList = resp.data;
          //   });
          $scope.submit = () => {
            $scope.fileIds = [];
            $scope.fileIds = $scope.editeditDocument.fileBeanList.map(item => item.id);
            $scope.editeditDocument.fileIds = $scope.fileIds.join(',');
            $http({
              method: 'PUT',
              url: `${SERVER_CONTEXT}/api/safesite/officeworkdata/updateRecord`,
              data: $scope.editeditDocument,
            }).then((resp) => {
              if (resp.data.success) {
                $scope.initViewModel();
                layer.msg(resp.data.message)
                $scope.closeThisDialog();
              } else {
                layer.alert(resp.data.message);
                $scope.closeThisDialog();
              }
            });
          }
        }
      });
    }
    // 删除信息
  $scope.deleteInformation = (id) => {
    $scope.modalTitle = '删除信息';
    $scope.modalContent = '确认要删除此信息吗?';
    ngDialog.openConfirm({
      template: 'paConfirm',
      className: 'ngdialog-theme-default pa-confirm-theme',
      scope: $scope,
    }).
    then((value) => {
      let reqData = [];
      reqData.push(id);
      $http({
        method: 'DELETE',
        url: `${SERVER_CONTEXT}/api/safesite/officeworkdata/delete`,
        params: {
          recordnos: reqData
        },
      }).
      then((data) => {
        $scope.initViewModel();
      });
    }, (reason) => {});
  };

  // 升序、降序
  $scope.up = (index) => {
    $scope.queryData.order = index;
    $scope.initViewModel();
  }
}

export default commonDocumentCtrl;